package eg.com.itiga.ui.actions;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import eg.com.itiga.business.company.RegCompanyService;
import eg.com.itiga.business.factory.BusinessFactory;
import eg.com.itiga.domain.RegCompany;
import eg.com.itiga.ui.beans.PendingRequestsForm;


/**
 * @author Ramadanco88
 * accept or reject companies resquets
 */
public class RegCompanyAction extends DispatchAction {

	public RegCompanyAction() {
	}

	public ActionForward accept(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		PendingRequestsForm pendingRequestsForm = (PendingRequestsForm) form;
		ActionForward actionForward = null;
		try {
			RegCompanyService regCompanyService = BusinessFactory.createRegCompanyService();

			
			
			System.out.println("-------------------------------");
			
			List<RegCompany> companies = pendingRequestsForm.getPendingCompanies();

			for (int i = 0; i < companies.size(); i++) {
				RegCompany currentCompany = companies.get(i);
				
				String name = (String) request.getParameter(currentCompany.getCId().toString());
				
				if(name != null)
				{
					regCompanyService.approveCompany(currentCompany.getCId());
				}
			}

			actionForward = mapping.findForward("loadPendingRequests");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return actionForward;
	}

	public ActionForward reject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		PendingRequestsForm pendingRequestsForm = (PendingRequestsForm) form;
		ActionForward actionForward = null;
		
		try {
			RegCompanyService regCompanyService = BusinessFactory.createRegCompanyService();

			List<RegCompany> companies = pendingRequestsForm.getPendingCompanies();

			for (int i = 0; i < companies.size(); i++) 
			{
				RegCompany currentCompany = companies.get(i);
				if (currentCompany.getRegIsApproved()) {
					currentCompany.setCState(RegCompany.REJECTED);
					currentCompany.setRegIsApproved(false);
					
					regCompanyService.update(regCompanyService);
				}
			}

			actionForward = mapping.findForward("loadPendingRequests");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return actionForward;
	}

}